import React, {useCallback, useEffect, useState} from 'react';
import {Breadcrumb, Button, Form, Input, message, Modal, Select, Space, Table, TableProps} from 'antd';
import {useNavigate} from "react-router-dom";
import type {Contract} from "@/types/resp/contract";
import contractApi from '@/api/contractApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import ContractAdd from "@/pages/contract/ContractAdd.tsx";
import ContractView from "@/pages/contract/ContractView.tsx";
import EmployeeSelector from "@/pages/employee/EmployeeSelector.tsx";
import { exportToExcel } from '@/utils/exportUtil.ts'
import {getEmployeeContractTypeText,getEmployeeContractStateText} from "@/utils/dictTranslator.ts";


const ContractList: React.FC = () => {

  const navigate = useNavigate();
  const [messageApi, messageContextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '劳动合同信息列表'}
  ]

  const [form] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    form.resetFields();
  };

  const [data, setData] = useState<Contract[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<Contract>> = await contractApi.find(form.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<Contract> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<Contract>['columns'] = [
    {title: '员工姓名', dataIndex: 'employeeName', key: 'employeeName'},
    {title: '合同签订日期', key: 'contractSignDate', render: (_, record) => (
      <div>{record.contractSignDate ? record.contractSignDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '合同类型', key: 'contractType', render: (_, record) => (
        <span>
        {(function () {
          if (record.contractType === 10) return '全职';
          else if (record.contractType === 20) return '兼职';
          else if (record.contractType === 30) return '实习';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '生效日期', key: 'effectiveDate', render: (_, record) => (
      <div>{record.effectiveDate ? record.effectiveDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '到期日期', key: 'expiryDate', render: (_, record) => (
      <div>{record.expiryDate ? record.expiryDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '合同状态', key: 'state', render: (_, record) => (
        <span>
        {(function () {
          if (record.state === 10) return '有效';
          else if (record.state === 20) return '终止';
          else if (record.state === 30) return '续签';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '工作地点', dataIndex: 'workLocation', key: 'workLocation', width: 200},
    {title: '工作时间', dataIndex: 'workingHours', key: 'workingHours'},
    {title: '岗位职责', dataIndex: 'jobDescription', key: 'jobDescription', ellipsis: true},
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: '250px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => editRow(record.id)}>编辑</Button>
          <Button danger onClick={() => delRow(record.id)}>删除</Button>
          <Button color="primary" variant="outlined" onClick={() => detailRow(record)}>详情</Button>
        </Space>
      ),
    },
  ];

  const [contractAddVisible, setContractAddVisible] = useState(false);
  const [contractViewVisible, setContractViewVisible] = useState(false);
  const [selectedContractId, setSelectedContractId] = useState(0)
  const [selectedContract, setSelectedContract] = useState({})

  const onAdd = () => {
    setSelectedContractId(0)
    setContractAddVisible(true)
  };

  const editRow = (id: number) => {
    setSelectedContractId(id)
    setContractAddVisible(true)
  };

  const delRow = useCallback(async (id: number) => {
    const confirmed = await modal.confirm({
      title: '删除提示',
      content: (
        <>
          确定要删除吗?
        </>
      ),
      okText: '确定',
      cancelText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      contractApi.del(id)
        .then((resp) => {
          if (resp && resp.code === 1) {
            messageApi.success('删除成功!')
            onSearch()
          } else {
            messageApi.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
          }
        })
        .catch(error => {
          console.error('操作失败:', error)
        })
    }
  }, [modal]);

  const detailRow = (record: Contract) => {
    setSelectedContract(record)
    setContractViewVisible(true)
  };

  const [employeeSelectorVisible, setEmployeeSelectorVisible] = useState(false);
  const findEmployee = () => {
    setEmployeeSelectorVisible(true);
  }
  const handleEmployeeSelected = (selectedEmployee: { employeeId?: number; employeeName?: string; }) => {
    setEmployeeSelectorVisible(false)
    if (selectedEmployee && 'employeeId' in selectedEmployee) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      employeeId: selectedEmployee['employeeId'],
      employeeName: selectedEmployee['employeeName'],
      }));
    }
  };
  const handleCloseEmployeeSelector = () => {
    setEmployeeSelectorVisible(false)
  };

  const handleCloseContractAdd = () => {
    setContractAddVisible(false)
  };

  const handleCloseContractView = () => {
    setContractViewVisible(false)
  };

  const onExport = () => {
    const headers = ['员工姓名','合同签订日期','合同类型','生效日期','到期日期','合同状态','工作地点','工作时间','岗位职责']
    contractApi.find(form.getFieldsValue()).then(data => {
      if (!data || !data.data || data.data.list.length < 1) {
        messageApi.error('无数据导出')
        return
      }
      const exportData = []
      for (const d of data.data.list) {
        exportData.push([d.employeeName,(d.contractSignDate ? d.contractSignDate.format('YYYY-MM-DD') : ''),getEmployeeContractTypeText(d.contractType),(d.effectiveDate ? d.effectiveDate.format('YYYY-MM-DD') : ''),(d.expiryDate ? d.expiryDate.format('YYYY-MM-DD') : ''),getEmployeeContractStateText(d.state),d.workLocation,d.workingHours,d.jobDescription])
      }
      exportToExcel(headers, exportData)
    })
  }

  useEffect(() => {
    onSearch();

    return () => {
    };
  }, []);

  return (
    <div className="contractList">
      {messageContextHolder}
      {modalContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="employeeName" label="员工姓名">
          <Input.Search placeholder="请选择员工姓名" onSearch={findEmployee} readOnly={true} />
        </Form.Item>
        <Form.Item name="contractType" label="合同类型">
          <Select placeholder="请选择合同类型" options={[
            { value: 10, label: <span>全职</span> },
            { value: 20, label: <span>兼职</span> },
            { value: 30, label: <span>实习</span> }
          ]} style={{width: 'var(--select-width)'}} />
        </Form.Item>
        <Form.Item name="state" label="合同状态">
          <Select placeholder="请选择合同状态" options={[
            { value: 10, label: <span>有效</span> },
            { value: 20, label: <span>终止</span> },
            { value: 30, label: <span>续签</span> }
          ]} style={{width: 'var(--select-width)'}} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onAdd}>新增</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onExport}>导出</Button>
        </Form.Item>
      </Form>
      <Table<Contract> columns={columns} dataSource={data} size="small" rowKey={record => record.id} pagination={{ position: ["bottomCenter"] }} style={{marginTop: 'var(--container-margin)'}} />
      <EmployeeSelector visible={employeeSelectorVisible} onEmployeeSelected={handleEmployeeSelected} onCloseEmployeeSelector={handleCloseEmployeeSelector} />
      <ContractAdd visible={contractAddVisible} onCloseContractAdd={handleCloseContractAdd} id={selectedContractId} />
      <ContractView visible={contractViewVisible} onCloseContractView={handleCloseContractView} viewRow={selectedContract} />
    </div>
  );
};

export default ContractList;
